# customizing the navigation and explorer portlet rendering

from zope.component import adapts, getMultiAdapter, queryUtility
from Acquisition import aq_inner
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from Products.CMFCore.utils import getToolByName
from plone.app.layout.navigation.interfaces import INavigationQueryBuilder
from plone.app.layout.navigation.interfaces import INavtreeStrategy
from plone.app.layout.navigation.navtree import buildFolderTree
from plone.app.portlets.portlets.navigation import Renderer
from plone.memoize.instance import memoize

#import local message factory to translate strings
# use __ since _ is already used in navigation.py
from plonetheme.apkntheme import APKNThemeMessageFactory as __
from plonetheme.apkntheme.utils.tools import add_params_to_url
from plonetheme.apkntheme import logger

PAD_URLS_WITH_LANGUAGE = False
TRIM_URLS_LENGTH = 30

class APKNNavigationRenderer(Renderer):

    def __init__(self, context, request, view, manager, data):
        Renderer.__init__(self, context, request, view, manager, data)
        
        self.properties = getToolByName(context, 'portal_properties').navtree_properties
        self.urltool = getToolByName(context, 'portal_url')
        
        self.pad_urls_with_language = False

    def getNavTree(self, _marker=[]):
        context = aq_inner(self.context)
        
        queryBuilder = getMultiAdapter((context, self.data), INavigationQueryBuilder)
        nav_query = queryBuilder()
        skip_children = False
        if hasattr(context, u'no_navigation_expand'):
            query_path = nav_query.get(u'path',{}).get(u'query', '@@@@')
            context_path = '/'.join(context.getPhysicalPath())
            if context_path.startswith(query_path):
                skip_children = context.no_navigation_expand
        strategy = getMultiAdapter((context, self.data), INavtreeStrategy)
        nav_tree = buildFolderTree(context, obj=context, query=queryBuilder(), strategy=strategy)
        if(len(nav_tree['children'])):
            if skip_children:
                nav_tree['children'][0]['show_children'] = not skip_children
            return nav_tree
        else:
            self.pad_urls_with_language = True
            query_b = queryBuilder()
            query_b['Language'] = ['en', '']
            return buildFolderTree(context, obj = context, 
            query = query_b, strategy = strategy)

    def getObjectURL(self, node):
        if self.pad_urls_with_language:
            node_url = node.get('getURL')
            node_object = self.context.restrictedTraverse(node.get('path'))
            object_language = node_object.getLanguage()
            if len(object_language):
                extra_params = {'set_language': object_language}
                return add_params_to_url(node_url, extra_params)
            else:
                return node_url
        else:
            return node.get('getURL')

    def getObjectTitle(self, node, trim = False):
        '''
        Get translated object titles for items in language different
        from current users language
        '''
        if self.pad_urls_with_language:
            final_title = self.translate_local_text(node.get('Title'))
        else:
            final_title = unicode(node.get('Title'), "UTF-8")
        if trim:
            if (len(final_title) > TRIM_URLS_LENGTH):
                final_title = ' ...'.join((final_title[:25], u''))
        return final_title

    def createNavTree(self):
        data = self.getNavTree()
        
        bottomLevel = self.data.bottomLevel or self.properties.getProperty('bottomLevel', 0)

        return self.recurse(children=data.get('children', []), level=1, bottomLevel=bottomLevel)


    def translate_local_text(self, text):
        '''
        Attempt translation of strings in Portlets
        '''
        logger.debug("Attempting to translate %s", text)
        return self.context.translate(__(text))

    _template = ViewPageTemplateFile('templates/navigation.pt')
    recurse = ViewPageTemplateFile('templates/navigation_recurse.pt')
